const { API_SNZO_URL, API_SNZO_FILE_URL } = require("../../../../utils/wxapi");
const wxapi = require("../../../../utils/wxapi");
const app = getApp();
// pages/center/auth/payMode/payMode.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    worksItem: null,
    worksTypeOfData: null,
    snzoImgUrl: API_SNZO_FILE_URL,
    isPaying: false
  },

  /**
   * 预览艺术品
   * @param {*} e 
   */
  previewImage(e) {
    const worksItem = this.data.worksItem;
    if (worksItem.tabStnumWorkses[0].standby2.indexOf('image') !== -1) {
      wx.previewMedia({
        sources: [
          {
            url: this.data.snzoImgUrl + worksItem.tabStnumWorkses[0].standby1,
            type: worksItem.tabStnumWorkses[0].standby2.split('/')[0]
          }
        ],
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel && Object.keys(eventChannel).length > 0) {
      eventChannel.on('worksMsg', (worksMsg) => {
        if (worksMsg) {
          this.setData({
            worksItem: worksMsg.worksItem,
            worksTypeOfData: worksMsg.worksTypeOfData
          });
        } else {
          wx.switchTab({
            url: '/pages/center/center',
          })
        }
      })
    } else {
      wx.switchTab({
        url: '/pages/center/center',
      })
      return;
    }
  },

  /**
   * 支付方式切换
   * @param {*} e 
   */
  radioChange(e) {
    const payModeOfData = this.data.payModeOfData;
    for (let i = 0, len = payModeOfData.length; i < len; ++i) {
      payModeOfData[i].checked = payModeOfData[i].value === e.detail.value
    }
    this.setData({
      payMode: e.detail.value,
      payModeOfData
    })
  },

  /**
   * 立即支付
   */
  payAuthFee() {
    const worksIds = [this.data.worksItem.tabStnumWorksMsg.id];
    this.setData({
      isPaying: true
    })
    // 可以支付
    const openId = wx.getStorageSync('openId');
    if (openId) {
      this.wxPay(openId, worksIds)
    } else {
      wx.login({
        success: (res) => {
          if (res.code) {
            const jsCode = res.code;
            const headers = {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            }
            wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
              if (res.code === 20000) {
                if (res.data) {
                  wx.setStorageSync('openId', res.data);
                  this.wxPay(res.data, worksIds)
                } else {
                  this.setData({
                    isPaying: false
                  })
                  wx.showToast({
                    title: '获取openId失败',
                    icon:'error'
                  })
                }
              } else {
                this.setData({
                  isPaying: false
                })
                wx.showModal({
                  title: '提示信息',
                  content: res.message,
                  showCancel: false
                })
              }
            })
          } else {
            wx.showToast({
              title: '登录失败',
              icon:'error',
              success: () => {
                this.setData({
                  isPaying: false
                })
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }
            })
          }
        },
      })
    }
  },

  /**
   * 取消支付
   */
  cancelPay() {
    wx.switchTab({
      url: '/pages/center/center',
    })
  },

  wxPay(openId, worksIds) {
    const params = {
      stk: app.globalData.userInfo.cardNo,
      openId
    }
    const headers = {
      Authorization: app.globalData.token
    }
    wxapi.authFeeXcxPay(params, worksIds, headers).then(res => {
      if (res.status === 200) {
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          paySign: res.data.paySign,
          signType: res.data.signType,
          timeStamp: res.data.timeStamp,
          success: (result) => {
            this.setData({
              isPaying: false
            })
            wx.showToast({
              title: '支付成功',
              success: () => {
                wx.switchTab({
                  url: '/pages/center/center',
                })
              }
            })
          },
          fail: (result) => {
            this.setData({
              isPaying: false
            })
            if (result.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon:'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon:'error'
              })
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})